/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');


/*
 *@todo  API12 回复一个主题帖
 * */
exports.post = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  if (!loginStatus.status) {
    return F.returnMsg(401, '注册用户才能回帖', 3);
  }
  if (!loginStatus.groupid == 4) { //gid=4 为禁止发言组
    return F.returnMsg(400, '用户被禁止发帖、回帖', 1);
  }
  var ip = Env.ip;

  var tid = fields.tid;
//  var imgback = fields.imgback;
  var post = fields.post;
  var vest_status = 0;
  var post_status=1;
  // 参数校验
//  if(!_.v.isIn(imgback,[0,1,2,3])){
//    return F.returnMsg(400, '参数错误', 1);
//  }
  if (post.length == 0 || !_.v.isLength(post, 1, 250)) {
    return F.returnMsg(400, '内容不能为空且必须250字内', 1);
  }
  var uid = loginStatus.uid;
  var nickName = loginStatus.nickname;
  if (post.length > 30 && !F.isManager(loginStatus.groupid)) {
    var postData = yield mysql.query('SELECT pid FROM mh_post_content WHERE uid=? AND post = ?', [uid, post]);
    if (postData.length > 1) {
      for (var i in postData) {
        yield this.delPost(Env, {act: 1, pid: parseInt(postData[i].pid), tokenkey: fields.tokenkey, status: 0});
      }
      return F.returnMsg(400, '禁止回广告帖。', 1);
    }
  }

  let rtimes = yield mysql.queryOne('SELECT count(*) as rtimes FROM mh_post mp LEFT JOIN mh_post_content mpc on mp.pid = mpc.pid WHERE mp.tid=? AND mpc.post=? and mpc.uid=? and mp.first=0',
    [tid, post, uid]);
  if (rtimes['rtimes'] > 0) {
    return F.returnMsg(400, '内容重复', 1);
  }
//  if (!_.v.isLength(post, 0,250)) {
//    return F.returnMsg(400, '内容必须250字内', 1);
//  }
  // 检查帖子closed状态
  var tempData = yield mysql.queryOne('SELECT tid,mt.uid,closed,mu.os_type,mu.device_token,mu.groupid FROM mh_thread mt LEFT JOIN mh_user mu ON mt.uid=mu.uid WHERE tid=?',
    [tid]);
  if (!tempData || tempData['closed'] == 1) {
    return F.returnMsg(400, '帖子已关闭', 1);
  }

  if (F.isManager(loginStatus.groupid)) {//管理员发帖
    uid = loginStatus.vestuid;
    nickName = loginStatus.vestnickname;
    vest_status = 1;
  }else{//如果不是管理员回帖，则检查回帖内容
    let data={post:post,isSPAM:fields._isSPAM};//isSPAM: 搜索是否含有敏感关键字
    var cid_data=yield F.checkCid(data);
    if(cid_data.SPAM==1){
      post_status=2;//vest_status用作更新thread.status用，如果是广告贴，则将status改成2
    }
  }
  //判断楼主是否马甲
  let thread_host_is_vest = 0;
  if (F.isManager(parseInt(tempData['groupid'])) || F.isVest(parseInt(tempData['uid']))) {
    thread_host_is_vest = 1;
  }

  var users = fields.users;
  var userArr = [];
  var userGroupArr = [];
  if (users) {
    var tempUserArr = users.split(',');
    for (var i in tempUserArr) {
      var tempUserId = _s.trim(tempUserArr[i]);
      var userData = yield mysql.query('SELECT uid,groupid FROM mh_user WHERE uid=?', [tempUserId]);
      if (userData.length > 0 && userData[0].uid != uid) {//不能回自己
        userArr.push(userData[0].uid);
        userGroupArr.push(userData[0].groupid);
      }
    }
  }
  if (userArr.length > C.post.postNum) {
    return F.returnMsg(400, '最多@' + C.post.postNum + '人', 1);
  }
  users = '';
  if (userArr.length > 0) {
    users = userArr.join(',');
  }

  var postData={};
  // 得到新的pid
  var newPost = yield mysql.query('INSERT INTO mh_post_table VALUES()');
  var pid = newPost.insertId;
  if (pid.insertId < 1) {
    return F.returnMsg(400, '回复失败', 1);
  }

  var authorId = tempData['uid'];
  var imgext = '';
  // 插入mh_post
  var isPostSuccess = yield mysql.query('INSERT INTO mh_post(pid,tid,imgext,uid,timeline,status,users,ip,vest) VALUES(?,?,?,?,UNIX_TIMESTAMP(),?,?,?,?)',
    [pid, tid, imgext, uid,post_status, users, ip, vest_status]);
  if (isPostSuccess.affectedRows < 1) {
    return F.returnMsg(400, '回复失败', 1);
  }
  // 插入mh_post_content
  var isPostContentSuccess = yield mysql.query('INSERT INTO mh_post_content(tid,pid,post,uid) VALUES(?,?,?,?)',
    [tid, pid, post, uid]);
  if (isPostContentSuccess.affectedRows < 1) {
    return F.returnMsg(400, '回复失败', 1);
  }
  if (F.isManager(loginStatus.groupid)) {
    mysql.query('INSERT INTO mh_vest_post(tid,pid,uid,vid,timeline) VALUES(?,?,?,?,UNIX_TIMESTAMP())',
      [tid, pid, loginStatus.uid, loginStatus.vestuid]);//管理员发帖
    //console.log(ip);
  }

  //设置发帖信息开始
  postData.pid=pid;
  postData.timeline=F.timestamp();
  postData.uid=uid;
  postData.tid=tid;
  postData.status=post_status;
  postData.post=post;
  postData.isVest=vest_status;
  postData.liketimes=0;
  postData.type=18;
  postData.like=false;
  postData.hot=0;
  postData.users = [];
  if (users.length > 0) {
    let userIdArr = users.split(',');
    for (let j in userIdArr) {
      let userData = yield mysql.queryOne('SELECT uid,nickname FROM mh_user WHERE uid=?', [userIdArr[j]]);
      if (userData) {
        postData.users.push({uid: userData['uid'], nickname: userData['nickname']});
      }
    }
  }

  let replyUserData=yield F.returnUserInfo(uid);
  replyUserData=replyUserData[0];
  postData.faceUrl = F.generateFaceUrl(replyUserData.face, uid);
  postData.nickname=replyUserData.nickname;
  postData.vip=replyUserData.vip;
  postData.talentid=replyUserData.talentid;
  postData.talent=replyUserData.talent;
  postData.level=replyUserData.level;
  //设置发帖信息结束


  //如果回复内容状态是2,则直接返回
  if(post_status==2){
    return F.returnMsg(200,'回复成功',3,postData);
  }
  yield F.memberCount(uid, 'posts=posts+1');//更新用户回帖数
  //更新发帖人信息开始
  var key = C.redisPre.user_info;
  key = _s.sprintf(key, parseInt(uid));
  var temp = yield F.redisCo.EXISTS(key);
  if (temp == 1) {
    F.redisClient.HINCRBY(key, 'posts', 1);//用户回帖数+1
  }
  //更新发帖人信息结束

  //更新帖子信息开始
  key = C.redisPre.thread_info;
  key = _s.sprintf(key, parseInt(tid));
  temp = yield F.redisCo.EXISTS(key);
  if (temp == 1) {
    var postUsers = JSON.stringify([]);
    var postUserseData = yield MPosts.getPostUsers({"tid": parseInt(tid)});
    if (postUserseData.length > 0) {
      postUsers = JSON.stringify(postUserseData);
    }
    var updateThreadCache = {};
    updateThreadCache.postusers = postUsers;
    yield F.updateThreadCache(parseInt(tid), updateThreadCache);//更新帖子缓存
    F.redisClient.HINCRBY(key, 'replies', 1);//用户回帖数+1
  }
  //更新帖子信息结束

  if (tempData.uid != uid) { // 如果楼主不是自己
    yield F.addDynamicInfo((F.isManager(loginStatus.groupid) ? -uid : uid), thread_host_is_vest == 1 ? -2 : 2, tid,
      authorId, pid);//回帖写动态
  }

  if (vest_status == 1) { // 马甲回帖不增加用户回帖数
    yield mysql.query('UPDATE mh_thread SET replies=replies+1,lastpost=UNIX_TIMESTAMP() WHERE tid=?', [tid]);//更新贴子回复次数和最后回复时间
  }
  else {
    yield mysql.query('UPDATE mh_thread SET replies=replies+1, userreplies=userreplies+1, lastpost=UNIX_TIMESTAMP() WHERE tid=?',
      [tid]);//更新贴子回复次数和最后回复时间
  }


  // logstash 流程
  var json ={
    uid:loginStatus.uid,
    vest:vest_status,
    tid:tid,
    action:'reply'
  };
  logstash.article(json);

//  if(!imgback||imgback==0){
//    var returnData={};
//  }else{
//    // 又拍云参数
//    var returnData=yield F.getUpyunSign({
//      type:2,
//      pid: pid,
//      imgBack: imgback
//    });
//  }
  yield F.afterPost();
  if (tempData.uid != uid && !F.isVest(tempData.uid)) { // 友盟推送(推送给楼主)： 自己不是楼主 且 楼主不是马甲
    var result = yield mysql.queryOne('SELECT pushpost,pushdisturb FROM mh_user_info WHERE uid=?', [tempData.uid]);
    if (result && result['pushpost'] == 1 && F.disturb(parseInt(result['pushdisturb']))) {
      var msg = _s.truncate(post, 27, '...');
      F.umengSendMsg(tempData['os_type'], tempData['device_token'], 2, {nickname: nickName, tid: tid, msg: msg});
    }
  }
  //////todo 推送给@用户
  if (userArr.length > 0) {
    for (var i in userArr) {
      if (!F.isVest(userArr[i])) { // 被推送的不是马甲
        var result = yield mysql.queryOne('SELECT mui.pushpost,mui.pushdisturb,mu.os_type,mu.device_token FROM mh_user_info mui INNER JOIN mh_user mu ON mui.uid=mu.uid WHERE mui.uid=?',
          [userArr[i]]);
        if (result && result['pushpost'] == 1 && F.disturb(parseInt(result['pushdisturb']))
        ) {
          F.umengSendMsg(result['os_type'], result['device_token'], 4, {
            nickname: nickName,
            tid: tid,
            msg: ''
          });
        }
      }
      ;
      if (userArr[i] != uid && userArr[i] != tempData.uid) {//被@的人不是自己也不是楼主
        var atuserisvest = F.isManager(parseInt(userGroupArr[i])) || F.isVest(parseInt(userArr[i]));
        yield F.addDynamicInfo((F.isManager(loginStatus.groupid) ? -uid : uid), atuserisvest ? -2 : 2, tid, userArr[i],
          pid, 1);//回帖写动态
      }
    }
  }
  var gain = yield F.generateIntegralLog(uid, 15, tid);//回复成功后获得积分
  return F.returnMsg(200, {act: '回复成功', e: gain}, 4,postData);
};
